<?php 


require_once("../config/dbconn.php");

dynamicAwards();
//动态奖结算
function dynamicAwards(){
    global $db,$db_prefix,$curtime,$glo_returnDynamicTxl_1,$glo_returnDynamicTxl_2,$glo_returnDynamicTxl_3,$glo_returnDynamicTxl_4,$glo_returnDynamicTxl_5,$glo_returnDynamicTxl_6,$glo_dynamicCapping,$glo_dynamicNum,$glo_heavyAwayMulriple,$glo_heavyAwayRatio,$glo_redeliveryMulriple,$sysposnum;
    //    今天的最后一秒
    $time1 = strtotime(date('Y-m-d 23:59:59'));
    $time2 =  strtotime(date('Y-m-d 00:00:00'));
    //      查询所有可以允许结算动态奖的会员
    $sql = "select id,username,price,sfprice,slprice,jyprice,ljslprice,fh_money,gluser,tjuser from {$db_prefix}users where regtime<{$time2} and dynamic_nexttime < {$time1} and ft_isend=0 limit 0,6000";
    $dynamic_all = $db->get_all($sql);
    foreach ($dynamic_all as $k=>$v){
        $userid = $v['id'];
        $username = $v['username'];
        $gluser = $v['gluser'];
        $tjuser = $v['tjuser'];
        $jyprice = $v['jyprice'];	//交易钱包
        $ljslprice = $v['ljslprice'];   //算力钱包累计收益
        $ljznprice = $v['fh_money'];   //智能钱包累计收益
        $leftall_yeji='';$rightall_yeji='';$smaller_yeji=0;$smaller_user='';$chongxiao_money=0;
        //该会员左区
        $gl_left = $db->get_one("select id,username from {$db_prefix}users where gluser='".$username."' and pos =1");
        //该会员右区
        $gl_right = $db->get_one("select id,username from {$db_prefix}users where gluser='".$username."' and pos =2");

        //左右两区都存在时，计算小区奖
        if(!empty($gl_left) && !empty($gl_right)){
            //左区
            if(!empty($gl_left)){
                $left_id = $gl_left['id'];
                $left_username = $gl_left['username'];
                //左区业绩
                $left_yeji = $db->get_one("select sum(price) as c1, sum(sfprice) as c2 from {$db_prefix}users where FIND_IN_SET({$left_id},glstr)or id={$left_id}");
                if(!empty($left_yeji)){
                    $leftall_yeji = $left_yeji['c1']+$left_yeji['c2'];
                }
            }
            //右区
            if(!empty($gl_right)){
                $right_id = $gl_right['id'];
                $right_username = $gl_right['username'];
                //右区业绩
                $right_yeji = $db->get_one("select sum(price) as c1, sum(sfprice) as c2 from {$db_prefix}users where FIND_IN_SET({$right_id},glstr)or id={$right_id}");
                if(!empty($right_yeji)){
                    $rightall_yeji = $right_yeji['c1']+$right_yeji['c2'];
                }
            }
            //确定小区
            if($leftall_yeji <= $rightall_yeji){
                $smaller_yeji = $leftall_yeji;
                $smaller_user = $left_username;
            }else if($leftall_yeji > $rightall_yeji){
                $smaller_yeji = $rightall_yeji;
                $smaller_user = $right_username;
            }
        }
        if($smaller_yeji == 0){
            $db->query("update wd_users set dynamic_nexttime={$time1} where username='{$username}'");
            continue;
        }
        //计算当前会员所处的等级
        $rank = calculationLevel($v['price'],$v['sfprice']);
        if($rank == false){
            $db->query("update wd_users set dynamic_nexttime={$time1} where username='{$username}'");
            continue;
        }
        //获取当前会员动态奖返现比例
        $glo_returnDynamicTxl = 'glo_returnDynamicTxl_'.$rank;
        //本次动态奖收益
        $shouyi = $smaller_yeji *($$glo_returnDynamicTxl/100);
        //计算当前会员投资额度
        $investmentAmounts = $v['price'] + $v['sfprice'];

        //复投额度
        $overlapping_investment = $investmentAmounts * $glo_redeliveryMulriple;

        //动态奖封顶数量
        $capping = $investmentAmounts*($glo_dynamicCapping/100);

        if($capping >= $glo_dynamicNum){
            $capping = $glo_dynamicNum;
        }

        //触发每日收益数量上限
        if($shouyi >= $capping){
            $shouyi = $capping;
        }

        //动态奖累计收益
        $ljslprice1 = $ljslprice+ $shouyi;

        //重消奖额度
        $repeat_purchases = $investmentAmounts*$glo_heavyAwayMulriple;
        //计算重消奖
        if($repeat_purchases < $ljslprice1){
          $linshi = $ljslprice1 - $repeat_purchases;

          if($linshi <= $shouyi){
              $chongxiao_money = $linshi * ($glo_heavyAwayRatio/100);
          }else{
              $chongxiao_money = $shouyi * ($glo_heavyAwayRatio/100);
          }
        }
        //实际动态奖
        $surplus_shouyi = $shouyi-$chongxiao_money;
        //累计动态收益
        $ljslprice2 = $ljslprice + $surplus_shouyi;
        //累计收益（动静结合）
        $ljpriceall =$ljznprice+$ljslprice2;
        //达到复投条件
        $ft_isend=0;

        if($overlapping_investment <= $ljpriceall){
            $linshi1 = $ljslprice2 - $overlapping_investment;
            if($linshi1 <= $surplus_shouyi && $linshi1>=0){
                $surplus_shouyi = $surplus_shouyi -$linshi1;
                $ft_isend =1;
            }elseif ($linshi1 > $surplus_shouyi && $linshi1>=0) {
                $surplus_shouyi = 0;
                $ft_isend =1;
            }elseif($linshi1<0){
                $ft_isend =1;
            }
        }
        $db->query('start transaction');#开启事物
        try {
            //重消金账户增加金额
            if ($chongxiao_money > 0) {
                $sqlkk = "update {$db_prefix}users set gwprice=gwprice+'" . floatval($chongxiao_money) . "',ljgwprice = ljgwprice+'" . floatval($chongxiao_money) . "',priceall = priceall+'" . floatval($chongxiao_money) . "' where id={$userid}";
                $row = $db->query($sqlkk);
                if (!empty($row)) {
                    //记录财务信息
                    //购物钱包财务记录
                    $e_userid = $userid;
                    $e_price = floatval($chongxiao_money);
                    $e_type = 1;
                    $e_ptype = 6;
                    $e_addtime = $curtime;
                    $e_memo = "每日动态奖结算，小区：".$smaller_user.",总业绩为：".$smaller_yeji.",新增购物钱包金额：" . $chongxiao_money;
                    hyepricejl($e_userid, $e_price, $e_type, $e_ptype, $e_addtime, $e_memo);
                }else{
                        throw new Exception('更新失败');
                }
            }
            //算力钱包增加金额
            if ($ft_isend == 1) {
                //改变复投状态以及下次动态奖结算时间
                if ($surplus_shouyi >= 0) {
                    $sqlkk = "update {$db_prefix}users set ft_isend=1,dynamic_nexttime=$time1,slprice=slprice+'".floatval($surplus_shouyi)."',ljslprice = ljslprice+'".floatval($surplus_shouyi)."' where id={$userid}";
                    $row = $db->query($sqlkk);
                    if(!$row){
                        throw new Exception('更新失败');
                    }
                    $memo = "每日动态奖结算，小区：".$smaller_user.",总业绩为：".$smaller_yeji.",动态奖出局，新增算力钱包金额：" . $surplus_shouyi;
                }
            }

            if ($ft_isend == 0) {

                $sqlkk = "update {$db_prefix}users set slprice=slprice+'".floatval($surplus_shouyi)."',ljslprice = ljslprice+'".floatval($surplus_shouyi)."',dynamic_nexttime=$time1 where id={$userid}";
                 $row = $db->query($sqlkk);
                    if(!$row){
                        throw new Exception('更新失败');
                    }
                $memo = "每日动态奖结算，小区：".$smaller_user.",总业绩为：".$smaller_yeji.",新增算力钱包金额：" . $surplus_shouyi;
            }
            if ($surplus_shouyi > 0) {
                if (!empty($row)) {
                    //记录财务信息
                    //算力钱包财务记录
                    $e_userid = $userid;
                    $e_price = floatval($surplus_shouyi);
                    $e_type = 1;
                    $e_ptype = 4;
                    $e_addtime = $curtime;
                    $e_memo = $memo;
                    hyepricejl($e_userid, $e_price, $e_type, $e_ptype, $e_addtime, $e_memo);
                }
            	//分享算力奖
                shareHashRate($surplus_shouyi, $username, $tjuser);
            }
            $db->query('commit');#提交
        }catch(Exception $e){
            $db->query('rollback');#回滚
        }
    }
    $db->free_result();
}
//分享算力奖
function shareHashRate($money='',$username='',$tjuser=''){
    global $db,$db_prefix,$curtime,$glo_sharingPowerAward_1,$glo_sharingPowerAward_2;

    if(empty($tjuser)){
       return true;
    }else{
        $one_tjuserinfo = $db->get_one("select id,username,slprice,ljslprice,tjuser,ft_isend from {$db_prefix}users where username='".$tjuser."'");
        $one_userid= $one_tjuserinfo['id'];
        $one_tjuser= $one_tjuserinfo['tjuser'];

        $share_profit_one = $money * ($glo_sharingPowerAward_1/100);
        if($one_tjuserinfo['ft_isend'] == 0){
            $row = $db->query("update {$db_prefix}users set slprice=slprice+'".floatval($share_profit_one)."',ljslprice = ljslprice+'".floatval($share_profit_one)."',priceall = priceall+'".floatval($share_profit_one)."' where username='".$tjuser."'");
            if(!$row){
                throw new Exception('更新失败');
            }
            //算力钱包财务记录
            $e_userid = $one_userid;
            $e_price = floatval($share_profit_one);
            $e_type = 5;
            $e_ptype = 4;
            $e_addtime = $curtime;
            $e_memo = "算力分享奖（1级），新增算力钱包金额：" . $share_profit_one."，奖金来自：".$username;
            hyepricejl($e_userid, $e_price, $e_type, $e_ptype, $e_addtime, $e_memo);
        }


        if(!empty($one_tjuser)){
            $two_tjuserinfo = $db->get_one("select id,username,slprice,ljslprice,tjuser,ft_isend from {$db_prefix}users where username='".$one_tjuser."' ");
            if($two_tjuserinfo['ft_isend'] ==0){
                $two_userid= $two_tjuserinfo['id'];
                $share_profit_two = $money * ($glo_sharingPowerAward_2/100);
                $row = $db->query("update {$db_prefix}users set slprice=slprice+'".floatval($share_profit_two)."',ljslprice = ljslprice+'".floatval($share_profit_two)."',priceall = priceall+'".floatval($share_profit_two)."' where username='".$two_tjuserinfo['username']."'");
                if(!$row){
                    throw new Exception('更新失败');
                }
                //算力钱包财务记录
                $e_userid = $two_userid;
                $e_price = floatval($share_profit_two);
                $e_type = 5;
                $e_ptype = 4;
                $e_addtime = $curtime;
                $e_memo = "算力分享奖（2级），新增算力钱包金额：" . $share_profit_two."，奖金来自：".$username;
                hyepricejl($e_userid, $e_price, $e_type, $e_ptype, $e_addtime, $e_memo);
            }
        }else{
            return true;
        }
    }
}
